﻿using AutoMapper;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.QrCode;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_Manage
{
    public class HomeBusiness : BaseBusiness<Base_User>, IHomeBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly IMapper _mapper;
        public HomeBusiness(IDbAccessor db, IOperator @operator, IMapper mapper)
            : base(db)
        {
            _operator = @operator;
            _mapper = mapper;
        }

        public async Task<string> SubmitLoginAsync(LoginInputDTO input)
        {
            input.password = input.password.ToMD5String();
            var theUser = await GetIQueryable()
                .Where(x => x.UserName == input.userName && x.Password == input.password)
                .FirstOrDefaultAsync();

            if (theUser.IsNullOrEmpty())
                throw new BusException("账号或密码不正确！");
            if (theUser.EmployeStatus==true) {
                throw new BusException($"{theUser.RealName}不存在系统用户中");
            }
            //生成token,有效期一天
            JWTPayload jWTPayload = new JWTPayload
            {
                UserId = theUser.Id,
                UserName = theUser.RealName,
                Expire = DateTime.Now.AddDays(1)
            };
            string token = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);

            return token;
        }

        public async Task<string> ScanLoginAsync(string qrcode)
        {
            string UserInfo = Extention.Base64Decode(qrcode);
            var entity = JsonConvert.DeserializeObject<qBase<qUser>>(UserInfo);//.SerializeObject(UserInfo);
            var theUser = await GetIQueryable()
                .Where(x => x.Id == entity.Value.Id)
                .FirstOrDefaultAsync();
            if (theUser.IsNullOrEmpty())
                throw new BusException("当前用户不存在！");
            //生成token,有效期一天
            JWTPayload jWTPayload = new JWTPayload
            {
                UserId = theUser.Id,
                Expire = DateTime.Now.AddDays(1)
            };
            string token = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);

            return token;
        }

        public async Task ChangePwdAsync(ChangePwdInputDTO input)
        {
            var theUser = _operator.Property;
            if (theUser.Password != input.oldPwd?.ToMD5String())
                throw new BusException("原密码错误!");

            theUser.Password = input.newPwd.ToMD5String();
            await UpdateAsync(_mapper.Map<Base_User>(theUser));
        }

        /// <summary>
        /// PDA输入账号密码登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<object> GetPDALogin(LoginInputDTO input)
        {
            input.password = input.password.ToMD5String();
            var q = await Db.GetIQueryable<Base_User>().Where(x => x.UserName == input.userName && x.Password == input.password && x.EmployeStatus == false).FirstOrDefaultAsync();
            if (q != null)
            {
                //生成token,有效期一天
                JWTPayload jWTPayload = new JWTPayload
                {
                    UserId = q.Id,
                    Expire = DateTime.Now.AddDays(1)
                };
                string token = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);
                Base_UserPDALogDTO buser = new Base_UserPDALogDTO();
                buser.Id = q.Id;
                buser.CreateTime = q.CreateTime;
                buser.CreatorId = q.CreatorId;
                buser.Deleted = q.Deleted;
                buser.UserName = q.UserName;
                buser.Password = q.Password;
                buser.QrCode = q.QrCode;
                buser.RealName = q.RealName;
                buser.Sex = q.Sex;
                buser.UserCode = q.UserCode;
                buser.Birthday = q.Birthday;
                buser.DepartmentId = q.DepartmentId;
                buser.Token = token;

                return buser;
            }
            else {
                throw new BusException("用户名或密码输入有误!");
            }
        }
    }
}
